package com.xing.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xing.common.dto.BrowseDto;
import com.xing.common.lang.Result;
import com.xing.mapper.BlogMapper;
import com.xing.model.Blog;
import com.xing.service.BlogService;
import com.xing.util.BrowseKeyUtils;
import com.xing.util.KeyUtils;
import com.xing.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 柠檬有点甜
 * @since 2021-08-17
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements BlogService {
    @Autowired
    BlogMapper blogMapper;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    @Override
    public Result ShowBrowseCount() {
        String key = KeyUtils.MAP_KEY_HOTTOP;



        /*从rdis中获取排行榜数据  */
        Set<ZSetOperations.TypedTuple<Object>> tuples = redisTemplate.boundZSetOps(key).reverseRangeWithScores(0L,9L);
        ArrayList<Blog> blogs = new ArrayList<>();
        for (ZSetOperations.TypedTuple<Object> tuple : tuples) {
            /*拆分String获取id和标题*/
            Object value = tuple.getValue();
            String[] split = String.valueOf(value).split(":");
            Blog blog = new Blog();
            blog.setId(Long.valueOf(split[0])).setTitle(split[1]).setBrowseCount(tuple.getScore().longValue());
            blogs.add(blog);
        }
        return Result.succ(blogs);
    }

    @Override
    public void saveHotTop() {
        /*查询十条最火排行榜*/
        /*解题思路，查询所有的博客信息，每次来查都来redis中拿，每天凌晨时更新redis最火数量*/
        String key = KeyUtils.MAP_KEY_HOTTOP;
        //清除可能已有的key
        redisUtil.del(key);
        /*查询所有博客的id和标题和点赞数，根据浏览数来实现排行榜*/
        List<Blog> blogs = blogMapper.selectList(null);

        /*如果博客不为空*/
        if (!blogs.isEmpty()&&blogs!=null){
            for (Blog blog:blogs){
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(blog.getId());
                stringBuilder.append(":");
                stringBuilder.append(blog.getTitle());
                /*拼接字符串格式 id:题目*/
                /*保存redis 有序集合zset */
                redisTemplate.opsForZSet().add(key,stringBuilder, blog.getBrowseCount());
            }
//            Set<ZSetOperations.TypedTuple<Object>> tuples = redisTemplate.boundZSetOps(key).reverseRangeWithScores(0L,9L);
//            for (ZSetOperations.TypedTuple<Object> tuple : tuples) {
//                /*拆分String获取id和标题*/
//                System.out.println(tuple.getValue() + " : " + tuple.getScore());
//            }
        }
    }


    @Override
    public void saveBrowseRedis(String ip, String aid) {
        String key = BrowseKeyUtils.getBrowseKey(ip, aid);
        /*如果key里面没有值就添加值*/
        if (ObjectUtil.isEmpty(redisUtil.get(key))){
             // 给redis设置记录值
            redisUtil.set(key,0,BrowseKeyUtils.BROWSE_TIME);
             //调用浏览记录的方法
            incrementCount(aid);
        }

    }

    @Override
    public void incrementCount(String aid) {
        /*给hash表中添加增量*/
        redisUtil.hincr(BrowseKeyUtils.MAP_KEY_BROWSE_COUNT,aid,1);

    }

    @Override
    public List<BrowseDto> getBrowseCountFromRedis() {
        Cursor<Map.Entry<Object, Object>> cursor  = redisUtil.hscan(BrowseKeyUtils.MAP_KEY_BROWSE_COUNT, ScanOptions.NONE);
        ArrayList<BrowseDto> list = new ArrayList<>();
        while (cursor.hasNext()){
            Map.Entry<Object, Object> entry = cursor.next();
            Long key = Long.valueOf((String) entry.getKey());

            BrowseDto browseDto = new BrowseDto();
            browseDto.setKey(key); //文章id
            browseDto.setBrowseCount(Long.valueOf(String.valueOf(entry.getValue())));//储存的浏览量
            list.add(browseDto);

            //存到List后从Redis中删除
            redisUtil.hdel(BrowseKeyUtils.MAP_KEY_BROWSE_COUNT,entry.getKey());
        }
        return list;
    }

    @Override
    public int addBrowseCount(List<BrowseDto> browseDto) {
        return  blogMapper.addBrowseCount(browseDto);
    }

    @Override
    public int addCollectCount(List<BrowseDto> browseDto) {
        return  blogMapper.addCollectCount(browseDto);
    }
    @Override
    public int addLikeCount(List<BrowseDto> browseDto) {
        return  blogMapper.addLikeCount(browseDto);
    }
}
